package com.example.demo.ykj.rainfall.repository;

import com.example.demo.ykj.rainfall.entity.Rainfall;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.List;

/**
 * @Author: zjq
 * @Date: create in 2022/7/5 10:40
 */
@Service
@Transactional
@Slf4j
public class RainfallSaveService {
    //此方法是批量保存数据，具体速度见controller
    @Autowired
    private EntityManager entityManager;

    public void batchSave(List<Rainfall> lst) {
        int j = 0;
        for (Rainfall distributedTransaction : lst) {
            //TODO 判断数据的合法性
            entityManager.persist(distributedTransaction);
            j++;
            if (j % 5000 == 0 || j == lst.size()) {
                try {
                    entityManager.flush();
                } catch (Exception e) {
                    log.error("fail", e);
                } finally {
                    entityManager.clear();
                }
            }
        }
    }
}
